package com.netty.pro.netty.websocket;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author xuzn
 * @ClassName: WebsocketServerHandler
 * @ProjectName netty-pro
 * @date 2020/3/16/20:30
 */
public class TextWebsocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

    System.out.println("服务器端收到消息 :" + msg.text());
    // 回显消息
    ChannelFuture channelFuture = ctx.writeAndFlush(new TextWebSocketFrame(
            "当前服务器时间是 " + LocalDateTime.now() + " " + msg.text()));
    boolean futureSuccess = channelFuture.isSuccess();
    System.out.println(futureSuccess);
    System.out.println("ctx发送完成");
  }

  // 当客户端链接上就触发
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    // id表示唯一值,asLongText是唯一的,asShortText有可能重复
    System.out.println("handlerAdd 被调用" + ctx.channel().id().asLongText());
    System.out.println("handlerAdd 被调用" + ctx.channel().id().asShortText());
  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    System.out.println("handlerRemoved 被调用" + ctx.channel().id().asLongText());
    System.out.println("handlerAdd 被调用" + ctx.channel().id().asLongText());
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    System.out.println("发生异常" + cause.getMessage());
    ctx.close();
  }
}
